package cn.bobdeng.spc.mainserver;

import cn.bobdeng.smartlock.webcommons.BaseResult;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.stream.Collectors;

@RestController
@RestControllerAdvice
public class BaseController {
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public BaseResult inputError(MethodArgumentNotValidException e) {
        String errors = e.getBindingResult().getFieldErrors().stream()
                .map(fieldError -> fieldError.getDefaultMessage())
                .collect(Collectors.joining("\n"));
        return BaseResult.getFail(errors);
    }

    @ExceptionHandler(BadCredentialsException.class)
    public BaseResult loginError(BadCredentialsException e) {
        return BaseResult.getFail("用户名或密码错误");
    }

    @ExceptionHandler(RuntimeException.class)
    public BaseResult otherException(RuntimeException e) {
        return BaseResult.getFail("未知错误：" + e.getMessage());
    }

}
